"""
Case Type   : python驱动psycopg2
Case Name   : psycopg2驱动与数据库交互创建表空间
Create At   : 2024/4/2
Owner       : @ningyali
Description :
    1.解压openGauss-*-CentOS-x86_64-Python.tar.gz得到lib,替换psycopg2
    2.配置白名单
    3.配置lib
    4.连接数据库，设置autocommit属性为True（默认会开启事务模式）
    5.创建表空间
    6.查询创建的表空间
    7.清理环境
Expect      :
    1.拷贝成功
    2.配置成功
    3.配置成功
    4.连接数据库成功
    5.执行成功
    6.执行成功
    7.执行成功
History     :
"""
import os
import unittest

from testcase.CONNECTORS.PDBC.PSYCOPG2. \
    Opengauss_Function_Connect_Psycopg_Common import Psycopg2Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class Psycopg56(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        text = f'-----{os.path.basename(__file__)} start-----'
        self.log.info(text)
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.conn_info = {'dbname': self.pri_sh.node.db_name,
                          'user': self.pri_sh.node.db_user,
                          'password': self.pri_sh.node.db_password,
                          'host': self.pri_sh.node.ssh_host,
                          'port': self.pri_sh.node.db_port}
        self.psycopg_com = Psycopg2Common(**self.conn_info)
        self.ts_name = 'ts_psycopg56'
        self.ts_path = 'tablespace/tablespace_1'

        text = '----前置操作: 备份白名单 expect: 备份成功----'
        self.log.info(text)
        res = self.psycopg_com.bak_conf(bak_flag=True)
        self.log.info(res)
        self.assertTrue(res, f'执行失败: {text}')

    def test_1(self):
        text = '----step1: 解压PDBC得到lib,替换psycopg2 expect: 执行成功----'
        res = self.psycopg_com.decompress_pkg()
        self.assertTrue(res, f'执行失败: {text}')
        res = self.psycopg_com.set_new_psycopg2()
        self.assertTrue(res, f'执行失败: {text}')

        text = '----step2: 配置白名单 expect: 配置成功----'
        self.log.info(text)
        res = self.psycopg_com.set_pghba(open_flag=True)
        self.assertTrue(res, f'执行失败: {text}')

        text = '----step3: 配置lib expect: 成功----'
        self.log.info(text)
        res = self.psycopg_com.set_lib_path()
        self.assertTrue(res, f'执行失败: {text}')

        text = '----step4: 连接数据库 expect: 成功----'
        self.log.info(text)
        res = self.psycopg_com.conn_db()
        expect = f"user={self.pri_sh.node.db_user} " \
                 f"dbname={self.pri_sh.node.db_name} " \
                 f"host={self.pri_sh.node.ssh_host} " \
                 f"port={self.pri_sh.node.db_port}"
        res = [self.assertIn(i, res) for i in expect.split()]
        self.assertEqual(len(res), 4, f'执行失败: {text}')

        text = '----step5: 创建表空间 expect: 成功----'
        self.log.info(text)
        sql1 = f"drop tablespace if exists {self.ts_name};"
        sql2 = f"create tablespace {self.ts_name} relative location " \
               f"'{self.ts_name}';"
        run_sql = f'conn.autocommit=True\n' \
                  f'cur=conn.cursor()\n' \
                  f'cur.execute(\\"{sql1}\\")\n' \
                  f'cur.execute(\\"{sql2}\\")\n' \
                  f'cur.close()\n'
        res = self.psycopg_com.run_sql(sql=run_sql)
        self.assertNotIn('errors', res, f'执行失败: {text}')

        text = '----step6: 查询创建的表空间 expect: 成功----'
        self.log.info(text)
        sql = f"select * from pg_tablespace where spcname='{self.ts_name}';"
        f_sql = self.psycopg_com.format_sql(sql)
        run_sql = self.psycopg_com.join_run_sql(f_sql)
        res = self.psycopg_com.run_sql(sql=run_sql)
        self.assertIn(self.ts_name, res, f'执行失败: {text}')
        self.assertNotIn('errors', res, f'执行失败: {text}')

        text = '----step7: 清理环境 expect: 成功----'
        self.log.info(text)
        sql = f"drop tablespace if exists {self.ts_name}"
        run_sql = f'conn.autocommit=True\n' \
                  f'cur=conn.cursor()\n' \
                  f'cur.execute(\\"{sql}\\")\n' \
                  f'cur.close()\n'
        res = self.psycopg_com.run_sql(sql=run_sql)
        self.assertNotIn('errors', res, f'执行失败: {text}')

    def tearDown(self):
        text = '----run teardown----'
        self.log.info(text)

        text1 = f'----后置操作：删除解压文件目录----'
        self.log.info(text1)
        res1 = self.psycopg_com.clean_decompress_file()

        text2 = f'----后置操作：还原白名单----'
        self.log.info(text2)
        res2 = self.psycopg_com.bak_conf(bak_flag=False)

        self.assertTrue(res1, f'执行失败: {text1}')
        self.assertTrue(res2, f'执行失败: {text2}')

        text = f'-----{os.path.basename(__file__)} end-----'
        self.log.info(text)
